<template>
  <div class="blog-detail-page">
    <van-nav-bar
      title="博客详情"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <div class="blog-content" v-if="blog">
      <div class="blog-header">
        <h1 class="blog-title">{{ blog.title }}</h1>
        <div class="blog-meta">
          <div class="author-info">
            <img :src="blog.author.avatar" :alt="blog.author.name" class="author-avatar" />
            <span class="author-name">{{ blog.author.name }}</span>
          </div>
          <div class="publish-time">{{ formatDate(blog.createTime, 'YYYY-MM-DD') }}</div>
        </div>
      </div>
      
      <div class="blog-body" v-html="blog.content"></div>
      
      <div class="blog-tags">
        <van-tag plain type="primary" v-for="tag in blog.tags" :key="tag">{{ tag }}</van-tag>
      </div>
      
      <div class="blog-actions">
        <div class="action-item" @click="toggleLike">
          <van-icon :name="isLiked ? 'like' : 'like-o'" :color="isLiked ? '#ee0a24' : ''" size="20" />
          <span>{{ blog.likes }}</span>
        </div>
        <div class="action-item" @click="scrollToComments">
          <van-icon name="comment-o" size="20" />
          <span>{{ blog.comments.length }}</span>
        </div>
        <div class="action-item" @click="shareBlog">
          <van-icon name="share-o" size="20" />
          <span>分享</span>
        </div>
      </div>
    </div>
    
    <div class="blog-comments" ref="commentsSection">
      <div class="section-title">评论 ({{ blog?.comments.length || 0 }})</div>
      
      <div class="comment-list" v-if="blog && blog.comments.length > 0">
        <div class="comment-item" v-for="(comment, index) in blog.comments" :key="index">
          <div class="comment-user">
            <img :src="comment.user.avatar" :alt="comment.user.name" class="user-avatar" />
            <div class="user-info">
              <div class="user-name">{{ comment.user.name }}</div>
              <div class="comment-time">{{ formatDate(comment.time, 'MM-DD HH:mm') }}</div>
            </div>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
          <div class="comment-actions">
            <div class="action-item" @click="likeComment(index)">
              <van-icon :name="comment.isLiked ? 'like' : 'like-o'" :color="comment.isLiked ? '#ee0a24' : ''" size="16" />
              <span>{{ comment.likes }}</span>
            </div>
            <div class="action-item" @click="replyComment(comment)">
              <van-icon name="comment-o" size="16" />
              <span>回复</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="empty-comments" v-else-if="blog">
        <van-empty description="暂无评论" />
      </div>
    </div>
    
    <div class="comment-input-container">
      <van-field
        v-model="commentText"
        placeholder="写下你的评论..."
        class="comment-input"
        :disabled="!isLoggedIn"
      >
        <template #button>
          <van-button 
            type="primary" 
            size="small" 
            :disabled="!commentText.trim() || !isLoggedIn"
            @click="submitComment"
          >
            发布
          </van-button>
        </template>
      </van-field>
    </div>
    
    <van-action-sheet v-model:show="showShareOptions" title="分享到">
      <div class="share-options">
        <div class="share-item" v-for="item in shareOptions" :key="item.name" @click="shareVia(item.name)">
          <van-icon :name="item.icon" size="24" :color="item.color" />
          <span>{{ item.label }}</span>
        </div>
      </div>
    </van-action-sheet>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { formatDate } from '../../../utils/common'
import { useUserStore } from '../../../store/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const isLoggedIn = computed(() => userStore.isLoggedIn)

const blog = ref(null)
const isLiked = ref(false)
const commentText = ref('')
const commentsSection = ref(null)
const showShareOptions = ref(false)

// 分享选项
const shareOptions = [
  { name: 'wechat', label: '微信', icon: 'wechat', color: '#07c160' },
  { name: 'weibo', label: '微博', icon: 'weibo', color: '#ff8200' },
  { name: 'qq', label: 'QQ', icon: 'friends-o', color: '#12b7f5' },
  { name: 'link', label: '复制链接', icon: 'link', color: '#1989fa' }
]

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 获取博客详情
const fetchBlogDetail = async () => {
  try {
    // 实际项目中应该调用真实的API
    // const { data } = await get(`/api/blogs/${route.params.id}`)
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    blog.value = {
      id: route.params.id,
      title: 'Vue 3 组合式API完全指南',
      author: {
        id: 'user1',
        name: '张三',
        avatar: 'https://picsum.photos/id/1001/100/100'
      },
      createTime: '2023-05-15T10:30:00',
      content: `
        <p>Vue 3的组合式API是Vue.js框架的一个重要更新，它提供了一种新的编写组件的方式，使代码更加灵活和可维护。</p>
        <h2>什么是组合式API？</h2>
        <p>组合式API是Vue 3引入的一种新的API风格，它允许我们使用函数而不是选项来组织组件逻辑。这种方法的主要优势是可以更好地重用和组织代码。</p>
        <h2>核心概念</h2>
        <p><strong>1. setup函数</strong></p>
        <p>setup函数是组合式API的入口点。它在组件实例创建之前执行，因此你不能在setup中访问this。</p>
        <pre><code>export default {
  setup() {
    // 这里编写组合式API代码
    return {
      // 返回值会暴露给模板和其他选项
    }
  }
}</code></pre>
        <p><strong>2. 响应式API</strong></p>
        <p>Vue 3提供了一系列函数来创建响应式数据：</p>
        <ul>
          <li>ref：创建一个响应式的数据引用</li>
          <li>reactive：创建一个响应式对象</li>
          <li>computed：创建计算属性</li>
          <li>watch/watchEffect：监听响应式数据的变化</li>
        </ul>
        <p><strong>3. 生命周期钩子</strong></p>
        <p>组合式API提供了一系列生命周期钩子函数：</p>
        <ul>
          <li>onMounted</li>
          <li>onUpdated</li>
          <li>onUnmounted</li>
          <li>等等...</li>
        </ul>
        <h2>示例</h2>
        <pre><code>import { ref, onMounted } from 'vue'

export default {
  setup() {
    const count = ref(0)
    
    function increment() {
      count.value++
    }
    
    onMounted(() => {
      console.log('组件已挂载')
    })
    
    return {
      count,
      increment
    }
  }
}</code></pre>
        <h2>总结</h2>
        <p>组合式API为Vue开发者提供了更多的灵活性和可能性。它不是替代选项式API，而是提供了另一种编写组件的方式，你可以根据项目需求选择合适的方式。</p>
      `,
      tags: ['Vue', '前端', 'JavaScript'],
      views: 1200,
      likes: 345,
      comments: [
        {
          id: 'c1',
          user: {
            id: 'user2',
            name: '李四',
            avatar: 'https://picsum.photos/id/1002/100/100'
          },
          content: '写得非常好，对我理解Vue 3的组合式API很有帮助！',
          time: '2023-05-16T08:30:00',
          likes: 12,
          isLiked: false
        },
        {
          id: 'c2',
          user: {
            id: 'user3',
            name: '王五',
            avatar: 'https://picsum.photos/id/1003/100/100'
          },
          content: '请问组合式API和选项式API相比，在性能上有什么优势吗？',
          time: '2023-05-16T10:15:00',
          likes: 5,
          isLiked: false
        },
        {
          id: 'c3',
          user: {
            id: 'user4',
            name: '赵六',
            avatar: 'https://picsum.photos/id/1004/100/100'
          },
          content: '代码示例很清晰，感谢分享！',
          time: '2023-05-17T14:20:00',
          likes: 8,
          isLiked: false
        }
      ]
    }
  } catch (error) {
    console.error('获取博客详情失败:', error)
    showToast('获取博客详情失败')
  }
}

// 切换点赞状态
const toggleLike = () => {
  if (!isLoggedIn.value) {
    showToast('请先登录')
    return
  }
  
  isLiked.value = !isLiked.value
  if (isLiked.value) {
    blog.value.likes++
    showToast('点赞成功')
  } else {
    blog.value.likes--
    showToast('已取消点赞')
  }
}

// 点赞评论
const likeComment = (index) => {
  if (!isLoggedIn.value) {
    showToast('请先登录')
    return
  }
  
  const comment = blog.value.comments[index]
  comment.isLiked = !comment.isLiked
  if (comment.isLiked) {
    comment.likes++
    showToast('点赞成功')
  } else {
    comment.likes--
    showToast('已取消点赞')
  }
}

// 回复评论
const replyComment = (comment) => {
  if (!isLoggedIn.value) {
    showToast('请先登录')
    return
  }
  
  commentText.value = `@${comment.user.name} `
}

// 提交评论
const submitComment = () => {
  if (!isLoggedIn.value) {
    showToast('请先登录')
    return
  }
  
  if (!commentText.value.trim()) {
    showToast('评论内容不能为空')
    return
  }
  
  // 添加评论
  blog.value.comments.unshift({
    id: `c${blog.value.comments.length + 1}`,
    user: {
      id: userStore.profile?.id || 'current-user',
      name: userStore.username,
      avatar: userStore.userAvatar
    },
    content: commentText.value,
    time: new Date().toISOString(),
    likes: 0,
    isLiked: false
  })
  
  // 清空评论框
  commentText.value = ''
  showToast('评论成功')
}

// 滚动到评论区
const scrollToComments = () => {
  commentsSection.value.scrollIntoView({ behavior: 'smooth' })
}

// 分享博客
const shareBlog = () => {
  showShareOptions.value = true
}

// 通过特定渠道分享
const shareVia = (channel) => {
  showToast(`已分享到${channel === 'link' ? '剪贴板' : channel}`)
  showShareOptions.value = false
}

onMounted(() => {
  fetchBlogDetail()
})
</script>

<style lang="scss" scoped>
.blog-detail-page {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: 60px;
  
  .blog-content {
    padding: 16px;
    background-color: var(--background-color-light);
    
    .blog-header {
      margin-bottom: 20px;
      
      .blog-title {
        font-size: 22px;
        font-weight: 600;
        color: var(--text-color);
        margin-bottom: 12px;
        line-height: 1.4;
      }
      
      .blog-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 14px;
        color: var(--text-color-tertiary);
        
        .author-info {
          display: flex;
          align-items: center;
          
          .author-avatar {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            margin-right: 8px;
          }
        }
      }
    }
    
    .blog-body {
      font-size: 16px;
      line-height: 1.8;
      color: var(--text-color);
      margin-bottom: 20px;
      
      h2 {
        font-size: 18px;
        font-weight: 600;
        margin: 24px 0 12px;
        color: var(--text-color);
      }
      
      p {
        margin-bottom: 16px;
      }
      
      ul, ol {
        padding-left: 20px;
        margin-bottom: 16px;
      }
      
      pre {
        background-color: var(--background-color);
        padding: 12px;
        border-radius: 4px;
        overflow-x: auto;
        margin-bottom: 16px;
        
        code {
          font-family: monospace;
          font-size: 14px;
          line-height: 1.5;
        }
      }
    }
    
    .blog-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 20px;
    }
    
    .blog-actions {
      display: flex;
      justify-content: space-around;
      padding: 12px 0;
      border-top: 1px solid var(--border-color-light);
      
      .action-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        span {
          font-size: 12px;
          color: var(--text-color-tertiary);
          margin-top: 4px;
        }
      }
    }
  }
  
  .blog-comments {
    margin-top: 12px;
    padding: 16px;
    background-color: var(--background-color-light);
    
    .section-title {
      font-size: 18px;
      font-weight: 500;
      color: var(--text-color);
      margin-bottom: 16px;
    }
    
    .comment-list {
      .comment-item {
        padding: 12px 0;
        border-bottom: 1px solid var(--border-color-light);
        
        &:last-child {
          border-bottom: none;
        }
        
        .comment-user {
          display: flex;
          align-items: center;
          margin-bottom: 8px;
          
          .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 8px;
          }
          
          .user-info {
            .user-name {
              font-size: 14px;
              font-weight: 500;
              color: var(--text-color);
            }
            
            .comment-time {
              font-size: 12px;
              color: var(--text-color-tertiary);
            }
          }
        }
        
        .comment-content {
          font-size: 14px;
          line-height: 1.6;
          color: var(--text-color);
          margin-bottom: 8px;
          padding-left: 40px;
        }
        
        .comment-actions {
          display: flex;
          justify-content: flex-end;
          
          .action-item {
            display: flex;
            align-items: center;
            margin-left: 16px;
            
            span {
              font-size: 12px;
              color: var(--text-color-tertiary);
              margin-left: 4px;
            }
          }
        }
      }
    }
    
    .empty-comments {
      padding: 20px 0;
    }
  }
  
  .comment-input-container {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 8px 12px;
    padding-bottom: calc(8px + var(--tabbar-height));
    background-color: var(--background-color-light);
    border-top: 1px solid var(--border-color-light);
    z-index: 1000;
    
    .comment-input {
      background-color: var(--background-color);
      border-radius: 20px;
      
      :deep(.van-field__control) {
        min-height: 20px;
      }
    }
  }
  
  .share-options {
    display: flex;
    flex-wrap: wrap;
    padding: 20px;
    
    .share-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 25%;
      margin-bottom: 16px;
      
      span {
        font-size: 12px;
        color: var(--text-color);
        margin-top: 8px;
      }
    }
  }
}
</style> 